//
// ElfParser.cpp
// Usage: Parse ELF module file
// CreateDate: 2009-04-23
// Author: MaJiuyue
//
#include <NewLife.h>
#include <string.h>
#include "ElfParser.h"

ElfParser::ElfParser(void * elf_buffer)
{
	m_ElfHeader = (Elf32Header *)elf_buffer;
	if(*((u32*)m_ElfHeader->e_ident) != 0x464C457F)
		panic("Not an ELF!\ne_ident: 0x%x", *((u32*)m_ElfHeader->e_ident));
}

addr_t ElfParser::GetEntryAddr()
{
	return (addr_t)m_ElfHeader->e_entry;
}

void ElfParser::SegmentFirst()
{
	m_index = -1;
}

bool ElfParser::SegmentNext()
{
	m_index++;
	if(m_index<0 || m_index >= m_ElfHeader->e_phnum)
		return false;
	return true;
}

addr_t ElfParser::GetOffset()
{
	Elf32ProgramHeader * ph = (Elf32ProgramHeader *)(m_ElfHeader->e_phoff+(addr_t)m_ElfHeader);
	return ph[m_index].ph_offset + (addr_t)m_ElfHeader;
}

addr_t ElfParser::GetMemSize()
{
	Elf32ProgramHeader * ph = (Elf32ProgramHeader *)(m_ElfHeader->e_phoff+(addr_t)m_ElfHeader);
	return ph[m_index].ph_memsz;
}

addr_t ElfParser::GetFileSize()
{
	Elf32ProgramHeader * ph = (Elf32ProgramHeader *)(m_ElfHeader->e_phoff+(addr_t)m_ElfHeader);
	return ph[m_index].ph_filesz;
}

addr_t ElfParser::GetVaddr()
{
	Elf32ProgramHeader * ph = (Elf32ProgramHeader *)(m_ElfHeader->e_phoff+(addr_t)m_ElfHeader);
	return ph[m_index].ph_vaddr;
}

